package com.hailiao.beidou.message.data.chat

import androidx.paging.Pager
import androidx.paging.PagingConfig
import com.d10ng.datelib.curTime
import com.hailiao.beidou.message.data.db.DB
import com.hailiao.beidou.message.data.db.entity.ChatEntity
import com.hailiao.beidou.message.data.db.entity.MessageEntity

/**
 * 聊天数据仓库
 * @Author d10ng
 * @Date 2024/3/2 13:53
 */
object ChatRepository {

    private val chatDao by lazy { DB.instant.chatDao() }

    // 正在对话的用户卡号
    var chattingAccount: String? = null

    // 对话框分页数据
    val pageDataFlow by lazy {
        Pager(
            config = PagingConfig(
                pageSize = 20,
                enablePlaceholders = true
            ),
            pagingSourceFactory = { chatDao.pagingSource() }
        ).flow
    }

    /**
     * 模糊查询
     * @param key String
     * @return List<ChatEntity>
     */
    suspend fun search(key: String) = chatDao.susQueryLike(key)

    /**
     * 获取对话框与联系人信息Flow
     * @param number String
     * @return Flow<ChatWithContactEntity?>
     */
    fun getChatWithContactFlow(number: String) = chatDao.queryWithContact(number)

    /**
     * 获取指定联系人的草稿信息
     * @param number String
     * @return String?
     */
    suspend fun getDraft(number: String) = chatDao.susQueryDraft(number)

    /**
     * 保存指定联系人的草稿信息
     * @param number String
     * @param draft String
     */
    suspend fun saveDraft(number: String, draft: String) = chatDao.susUpdateDraft(number, draft)

    /**
     * 清除指定联系人的未读数
     * @param number String
     */
    suspend fun clearUnreadCount(number: String) = chatDao.susClearUnreadCount(number)

    /**
     * 通过最新消息更新对话框
     * @param msg MessageEntity
     */
    suspend fun updateBy(msg: MessageEntity) {
        var chat = chatDao.susQuery(msg.number)
        if (chat == null) {
            chat = ChatEntity(msg.number)
        }
        chat.time = msg.sendTime
        if (!msg.isSendOut && chattingAccount != msg.number) {
            chat.unreadCount += 1
        }
        chat.content = msg.content
        chat.sendStatus = msg.status
        chatDao.insert(chat)
    }

    /**
     * 删除对话框
     * @param chat ChatEntity
     */
    suspend fun delete(chat: ChatEntity) = chatDao.deleteWithMessage(chat)

    /**
     * 通过卡号创建对话框
     * @param number String
     */
    suspend fun createBy(number: String) {
        var chat = chatDao.susQuery(number)
        if (chat == null) {
            chat = ChatEntity(
                number = number,
                time = curTime
            )
            chatDao.insert(chat)
        }
    }
}